<?php
/**
 * @package common
 */

/**
 * Improved string implementation.
 */
class StringEx {
	/** @var string - data */
	private $data;
	
	/**
	 * Create instance.
	 * @param string $string - a normal php string
	 */
	public function __construct(string $string = null) {
		$this->data = is_null($string) ? "" : $string;
	}
	
	/**
	 * Overriden method which allows echoing of this class's instance.
	 */
	public function __toString() {
		return $this->data;
	}
	
	/**
	 * Get first $lenght characters from the string
	 * @return StringEx - cropped string
	 */
	public function firstNChars(int $lenght) {
		return new StringEx(preg_replace("/^(.{0,$lenght}).*/", "$1", $this->data));
	}
	
	/**
	 * Setter.
	 */
	public function set(string $string = null) {
		$this->data = is_null($string) ? "" : $string;
	}
	
	/**
	 * Getter.
	 */
	public function get() {
		return $this->data;
	}
	/**
	 * Crop last word from the string.
	 * @return StringEx - new instance of a StringEx with cropped word
	 */
	public function cropLastWord() {
		return new StringEx(preg_replace("/[^ ]*$/", "", $this->data));
	}
	
	/**
	 * Get string with first $maxLenght characters as a maximum.
	 * Don't devide words.
	 * 
	 * @param int $maxLenght - maximum lenght of returned string
	 * @return StringEx - new string
	 */
	public function firstNCharsButSaveWords(int $maxLenght) {
		$str = $this->firstNChars($maxLenght + 1);
		if ($str->lenght() <= $maxLenght)
			$str->data .= " ";
		return $str->cropLastWord();
	}
	
	/**
	 * Length of string
	 * @return int - length
	 */
	public function lenght() {
		return strlen($this->data);
	}
}
?>